using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace BasicTest
{
	public class BloomFilter
	{
		readonly BitArray _bitArray;
		private readonly int _size;
		private readonly int _numHashFunctions;

		public BloomFilter(int size, int numHashFunctions)
		{
			_size = size;
			_numHashFunctions = numHashFunctions;
			_bitArray = new BitArray(size);
		}

		// 哈希函数，这里使用简单的MD5哈希结合取模来生成多个不同位置
		private int[] HashFunction(string element)
		{
			using (MD5 md5 = MD5.Create())
			{
				byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(element));
				int[] positions = new int[_numHashFunctions];
				for (int i = 0; i < _numHashFunctions; i++)
				{
					int hashValue = BitConverter.ToInt32(hashBytes, i * 4);
					positions[i] = Math.Abs(hashValue % _size);
				}
				return positions;
			}
		}

		public void Add(string element)
		{
			int[] positions = HashFunction(element);
			foreach (int position in positions)
			{
				_bitArray[position] = true;
			}
		}

		public bool Contains(string element)
		{
			int[] positions = HashFunction(element);
			foreach (int position in positions)
			{
				if (_bitArray[position] == false)
				{
					return false;
				}
			}
			return true;
		}
	}
}
